package com.xianniu.ltc.aspect;

import cn.devezhao.persist4j.Entity;
import cn.devezhao.persist4j.Query;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rebuild.core.Application;
import com.rebuild.core.BootEnvironmentPostProcessor;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.ConfigBean;
import com.rebuild.core.configuration.general.TransformManager;
import com.rebuild.core.metadata.EntityHelper;
import com.rebuild.core.metadata.MetadataHelper;
import com.rebuild.core.service.general.transform.RecordTransfomer;
import com.xianniu.ltc.enums.NicheWinRate;
import com.xianniu.ltc.mapper.RbShangjiMapper;
import com.xianniu.ltc.mapper.TJiaofushijianguanliMapper;
import com.xianniu.ltc.mapper.TRbhetong0Mapper;
import com.xianniu.ltc.model.entity.TJiaofushijianguanliDTO;
import com.xianniu.ltc.model.entity.TRbhetong0DTO;
import com.xianniu.ltc.model.entity.TRbshangji4DTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wangruijie
 * 审批后，触发器前触发切面操作
 *
 */
@Slf4j
@Aspect
@Component
public class ApprovalAfterTriggerBeforeAspect {

    @Resource
    private TJiaofushijianguanliMapper jiaofuMapper;
    @Resource
    private TRbhetong0Mapper tRbhetong0Mapper;

    //拦截指定的方法,这里指只拦截ApprovalStepService.approved这个方法
    @Pointcut("execution(public * com.rebuild.core.service.approval.OnApprovedBeforeTrigger.triggerManualOnApproved(..))")
    public void excuteService() {

    }

    //执行方法前的拦截方法
    @Before("excuteService()")
    public void doBeforeMethod(JoinPoint joinPoint) {
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        Object recordId = obj[0];
        log.info("参数输出：{}", obj);
        String sourceEntity = MetadataHelper.getEntityName(ID.valueOf(recordId.toString()));
        // 服务请求审批通过后
        if (sourceEntity.equalsIgnoreCase("jiaofushijianguanli")){
            log.info("服务请求审批通过后：商机不为空则， 根据商机判断是否可生成项目合同，同时赋值服务请求的合同字段值：{}", recordId.toString());
            doServiceRequestApprovedAfter(ID.valueOf(recordId.toString()));
        }
    }

    /**
     *
     * 服务请求审批通过后，
     *  if(商机值 != null)
     *      if(需要判断商机是否已创建合同){
     *          如果已创建则查到覆盖服务请求的关联合同，合同编号，合同名称
     *      }else{
     *          调用记录转换，根据商机id生成合同，同时覆盖服务请求的关联合同，合同编号，合同名称
     *      }
     *  else{
     *      跳过即可
     *  }
     * @param sourceRecord
     */
    private void doServiceRequestApprovedAfter(ID sourceRecord){
        log.info("服务请求审批通过后 根据是否录入了商机，且商机未生成合同前提下，通过商机id转换为项目合同（销售）：{}", sourceRecord.toString());
        String tenantCode = UserContextHolder.getTenant();
        Object[] o = Application.getQueryFactory().uniqueNoFilter(sourceRecord, EntityHelper.ApprovalState, "guanlianshangji");
        // 审批通过 && 商机不为空
        if (o != null && o[0].equals(10) && o[1] != null){
            TRbhetong0DTO saleContract = new TRbhetong0DTO();
            // 通过商机编号查询合同
            QueryWrapper<TRbhetong0DTO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SHANGJIBIANHAO", o[1].toString());
            List<TRbhetong0DTO> saleContracts = tRbhetong0Mapper.selectList(queryWrapper);
            if(CollectionUtils.isNotEmpty(saleContracts)){
                // 选择第一条
                saleContract = saleContracts.get(0);
            }else {
                // 商机转换项目合同转换记录ID
                ID transid = ID.valueOf("037-01814640646f027b");
                ConfigBean config = TransformManager.instance.getTransformConfig(transid, null, BootEnvironmentPostProcessor.getDefaultTenant());
                Entity targetEntity = MetadataHelper.getEntity(config.getString("target"));

                RecordTransfomer transfomer = new RecordTransfomer(targetEntity, (JSONObject) config.getJSON("config"));
                if (!transfomer.checkFilter(ID.valueOf(o[1].toString()), tenantCode)) {
                    log.info("没有权限进行转换，数据：{}", o[1].toString());
                }

                ID newId = transfomer.transform(ID.valueOf(o[1].toString()), tenantCode);
                log.info("商机转换项目合同(销售)转换记录成功：{}", newId.toString());
                // 创建后立即根据id查询销售合同
                saleContract = tRbhetong0Mapper.selectById(newId.toString());
            }
            // 赋值服务请求的关联合同，合同编号，合同名称
            TJiaofushijianguanliDTO dto = new TJiaofushijianguanliDTO();
            dto.setJiaofushijianguanliId(sourceRecord.toString());
            dto.setGuanlianxiangmuhetong(saleContract.getRbhetong0Id());
            dto.setXiangmuhetongbianhao(saleContract.getHetongbianhao());
            dto.setHetongmingcheng(saleContract.getRbhetong0Name());
            log.info("根据商机查询/转换生成合同后赋值关联合同，合同编号，合同名称：{}", JSON.toJSON(dto));
            jiaofuMapper.updateById(dto);
        }
        log.info("服务请求不是审批通过&&商机不为空，不进行操作：{}", sourceRecord.toString());
    }

}